package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.Customer;
import com.cfets.annualAssessment.entity.TableContainer;
import com.cfets.annualAssessment.service.CustomerService;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by liusonglin on 2016/11/21.
 */
@Controller
@RequestMapping("/admin/customer")
@Log4j
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @RequestMapping("/index")
    public String index(Model model){
        return "customer";
    }

    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> customerList(Customer customer){
//        log.error("Get Mapping error!");
        List<Customer> attributeList = customerService.getCustomerPage(customer);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(attributeList);
        tableContainer.setiTotalDisplayRecords(customer.getTotalCount());
        tableContainer.setiTotalRecords(customer.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<?> createOrUpdate(@Valid Customer customer, BindingResult result) {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
//        customer.setPostTime(new Date());
        boolean flag = false;
        if(customer.getId()!=null && customer.getId()!=0){
            flag = this.customerService.updateAttribute(customer);
        }else {
            flag = this.customerService.newAttribute(customer);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAttribute(@PathVariable("id") int id){
        boolean flag = this.customerService.deleteAttributeById(id);
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
}
